# !/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask, request
from conf.config import appKey, appSecret, systemCode, notifyUrl, serverUrl
import time
from util.signUtils import signutils
import json
from util.log_util import get_logger
from util.alertmanager import parseAlertManagerMsg
from util.http_util import api_request
import logging

app = Flask(__name__)
logger = get_logger()


@app.route('/api/alert/send', methods=["POST"])
def send_alert():
    datas = json.loads(request.data)
    msg_list = parseAlertManagerMsg(datas)
    logger.info(msg_list)
    if msg_list:
        params = {
            "timestamp": int(round(time.time() * 1000)),
            "systemCode": systemCode,
            "messageType": 4,
            "messageCodeDTOList": msg_list,
            "appKey": appKey,
            "notifyUrl": notifyUrl
        }
        sign = signutils(appSecret=appSecret, params=params)
        params['sign'] = sign
        logger.info(params)
        headers={
            'Content-Type': 'application/json'
        }
        result = api_request(method="POST", url=serverUrl, params=params, headers=headers)
        if result:
            return "{'success': True, 'obj': None, 'msg': 'success', 'code': 0}", 200
        else:
            return "{'success': False, 'obj': None, 'msg': 'server error', 'code': 10001}", 500


if __name__ == '__main__':
    """
    app.debug = True
    handler = logging.FileHandler('flask.log', encoding='UTF-8')
    handler.setLevel(logging.DEBUG)
    logging_format = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
    handler.setFormatter(logging_format)
    app.logger.addHandler(handler)
    """
    app.run(debug=False, host='0.0.0.0', port=9095)
